package com.lw.leetcode.tree.b;

import com.lw.leetcode.tree.TreeNode;

import java.util.LinkedList;

/**
 * Created with IntelliJ IDEA.
 * 919. 完全二叉树插入器
 * 剑指 Offer II 043. 往完全二叉树添加节点
 *
 * @author liw
 * @version 1.0
 * @date 2022/2/21 11:05
 */
public class CBTInserter {

    private TreeNode root;
    private LinkedList<TreeNode> deque;

    public CBTInserter(TreeNode root) {
        this.root = root;
        deque = new LinkedList<>();
        LinkedList<TreeNode> queue = new LinkedList<>();
        queue.offer(root);

        while (!queue.isEmpty()) {
            TreeNode node = queue.poll();
            if (node.left == null || node.right == null) {
                deque.offerLast(node);
            }
            if (node.left != null) {
                queue.offer(node.left);
            }
            if (node.right != null) {
                queue.offer(node.right);
            }
        }
    }

    public int insert(int v) {
        TreeNode node = deque.peekFirst();
        deque.offerLast(new TreeNode(v));
        if (node.left == null) {
            node.left = deque.peekLast();
        } else {
            node.right = deque.peekLast();
            deque.pollFirst();
        }
        return node.val;
    }

    public TreeNode get_root() {
        return root;
    }


}
